#include "_public.h"
using namespace std;

CSEM sem;

struct st_pid
{
    int pid;
    char name[51];
};


int main(int argc, char *argv[]){
    // 共享内存的标志
    int shmid;

    // 获取/创建共享内存，键值为0x5005
    if((shmid= shmget(0x5005, sizeof(struct st_pid), 0640|IPC_CREAT)) == -1){
        cout << "shmget 0x5005 failed." << endl;
        return -1; 
    }

    // 如果信号量已经存在，获取信号量；如果信号量不存在，则创建并初始化为value
    if(sem.init(0x5005) == false){
        cout << "sem.init(0x5005) failed." << endl;
        return -1;
    }

    // 用于指向共享内存的结构体变量
    struct st_pid *stpid = 0;

    // 把共享内存连接到当前进程的地址空间
    if((stpid = ((struct st_pid *)shmat(shmid, 0, 0))) == (void *)-1){
        cout << "shmat failed." << endl;
        perror("shmat");
        return -1;
    }

    cout << "aaa time = " << time(0) << ",val = " << sem.value() << endl;
    sem.P();
    cout << "bbb time = " << time(0) << ",val = " << sem.value() << endl;

    cout << "pid=" << stpid->pid << ",name=" << stpid->name << endl;
    stpid->pid = getpid();
    sleep(10);
    strcpy(stpid->name, argv[1]);
    cout << "pid=" << stpid->pid << ",name=" << stpid->name << endl;

    cout << "ccc time = " << time(0) << ",val = " << sem.value() << endl;
    sem.V();
    cout << "ddd time = " << time(0) << ",val = " << sem.value() << endl;

    // 把共享内存从当前进程中分离
    // shmdt(stpid);

    // 删除共享内存
    // if(shmctl(shmid, IPC_RMID, 0) == -1){
    //     cout << "shmctl failed." << endl;
    //     return -1;
    // }
    return 0;
}